package javase.day05;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * 
 * 统计一部小说中不重复文字的数量
 *
 */
public class Demo1 {
	public static void main(String[] args){
		String file="/home/tarena/hotel.txt";
		Map<Character, Integer> map = new HashMap<Character, Integer>();
		try {
			int all = count(file,"gbk", map);
			System.out.println(all);
			System.out.println(map.size());
			System.out.println(map);
			
			List<Entry<Character, Integer>> entrys = new ArrayList<Entry<Character, Integer>>(map.entrySet());
			Collections.sort(entrys,new Comparator<Entry<Character, Integer>>() {
				@Override
				public int compare(Entry<Character, Integer> o1,
						Entry<Character, Integer> o2) {
					// TODO Auto-generated method stub
					return -(o1.getValue()-o2.getValue());
				}
			});
			for(int i=0;i<10;i++){
				Entry<Character, Integer> entry = entrys.get(i);
				char c =entry.getKey();
				int val = entry.getValue();
				System.out.println(c+":"+val+":"+((double)val/all)*100);
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	/**
	 * 
	 * @param file  文件名
	 * @param map  统计结果
	 * @return  文字总数
	 */
	public static int count(String textFile,String encoding,Map<Character, Integer> map) 
			throws IOException{
		Reader in = new InputStreamReader(new BufferedInputStream(new FileInputStream(textFile)),encoding);
//		InputStream in = new FileInputStream(textFile);
//		BufferedInputStream bis = new BufferedInputStream(in);
//		Reader read = new InputStreamReader(bis,encoding);
		Set<Character> ign = new HashSet<Character>();
		ign.add('.');
		ign.add('/');
		ign.add('\t');
		ign.add('\r');
		ign.add('*');
		ign.add('：');
		ign.add(' ');
		ign.add('\n');
		int c,count=0;
		while((c=in.read())!=-1){
			char ch = (char)c;
			if(ign.contains(ch)){
				continue;
			}
			Integer val = map.get(ch);
			val=val==null?1:val+1;
			map.put(ch, val);
//			if(map.containsKey(ch)){
//				int val = map.get(ch);
//				map.put(ch, val+1);
//			}else{
//				map.put(ch, 1);
//			}
			count++;
		}
		in.close();
		return count;
	}
	
}
